package com.douqu.game.main.msg;

import com.douqu.game.core.controller.PlayerController;
import com.douqu.game.core.entity.*;
import com.douqu.game.core.entity.common.CommonData;
import com.douqu.game.core.entity.ext.InstanceInfo;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.factory.WordFactory;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.protobuf.SGCommonProto.E_NOTIFY_TYPE;
import com.douqu.game.core.protobuf.SGCommonProto.E_BATTLE_TYPE;
import com.douqu.game.core.protobuf.SGMainProto;
import com.douqu.game.core.protobuf.SGInstanceProto.*;
import com.douqu.game.main.util.MsgUtils;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

/**
 * @author wangzhenfei
 *         2017-08-21 10:06
 */
@Component
public class InstanceMsgChannel  implements AMsgChannel{
    Logger logger = Logger.getLogger(this.getClass());

    @Override
    public void messageChannel(int code, PlayerController playerController, byte[] data) {

        if(playerController == null)
            return;


        switch (code)
        {
            case SGMainProto.E_MSG_ID.MsgID_Instance_GetInstanceInfo_VALUE:
                getList(playerController, data);
                break;
            case SGMainProto.E_MSG_ID.MsgID_Instance_PassLevel_VALUE:
//                data =  C2S_PassLevel.newBuilder().
//                        setMapId(2)
//                        .setLevelId(11)
//                        .setStarts(1)
//                        .build().toByteArray();
                addPassLevel(playerController, data);
                break;
            case SGMainProto.E_MSG_ID.MsgID_Instance_ReceiveAward_VALUE:
                receiveAward(playerController, data);
                break;
            case SGMainProto.E_MSG_ID.MsgID_Instance_RequestLevelBattle_VALUE:
                requestLevelBattle(playerController, data);
                break;
            case SGMainProto.E_MSG_ID.MsgID_Instance_ReceiveLevelBoxReward_VALUE:
                receiveLevelAward(playerController, data);
                break;
        }





    }

    private void receiveLevelAward(PlayerController playerController, byte[] data) {
        S2C_ReceiveLevelBoxReward.Builder response = S2C_ReceiveLevelBoxReward.newBuilder();
        C2S_ReceiveLevelBoxReward request = null;
        try {
            request = C2S_ReceiveLevelBoxReward.parseFrom(data);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        if(request == null){
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }
        int mapId = request.getMapId();
        int levelId = request.getLevelId();

        InstanceInfo instanceInfo = (InstanceInfo) playerController.getPlayer().getExtInfo(InstanceInfo.class);
        logger.info("领取关卡宝箱请求参数-->地图id : " + mapId);
        logger.info("领取关卡宝箱请求参数-->关卡id : " + levelId);
        //判断mapid和levelid是否合法
        InstanceMap instance = DataFactory.getInstance().getGameObject(DataFactory.INSTANCE_KEY, mapId);
        if(instance == null)
        {
            logger.info("领取关卡宝箱结果 ： " + "参数异常");
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }

        //判断该关卡是否有奖励
        Level configLLevel = DataFactory.getInstance().getGameObject(DataFactory.LEVEL_KEY, levelId);
       if(configLLevel == null || configLLevel.boxReward == 0){
           //返回给客户端
           logger.info("领取关卡宝箱结果 ： " + "该关卡没有宝箱可以领取");
           playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.BOX_NOTHING_REWARD));
           return;
       }

        InstanceMap instanceMap = instanceInfo.getInstanceMap().get(mapId);
        if(instanceMap == null){
            logger.info("领取关卡宝箱结果 ： " + "地图未解锁");
            //返回给客户端
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.MAP_NOT_UNLOCK));
            return;
        }

        Level level = instanceMap.getLevelMap().get(levelId);

        if(level == null){//未解锁
             logger.info("领取关卡宝箱结果 ： " + "地图未解锁");
             //返回给客户端
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.MAP_NOT_UNLOCK));
            return;
        }

        if(level.isReceive()){
            logger.info("领取关卡宝箱结果 ： " + "已经领取过了");
            //返回给客户端
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.GET_REWARD_ED));
            return;
        }

        level.setReceive(true);

        DropGroup dropGroup = DataFactory.getInstance().getGameObject(DataFactory.DROP_GROUP_KEY, configLLevel.boxReward);
        DropResult result = dropGroup.reward(playerController);

        for(CommonData card : result.getCards())
        {
            response.addCard(card.parseCommonObject());
        }
        for(CommonData prop : result.getProps())
        {
            response.addProp(prop.parseCommonObject());
        }
        for(CommonData asset : result.getAssets())
        {
            response.addAsset(asset.parseCommonObject());
        }

        //返回给客户端
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Instance_ReceiveLevelBoxReward_VALUE, response.build().toByteArray());

    }

    private void receiveAward(PlayerController playerController, byte[] data)
    {

        C2S_ReceiveInstanceAward request = null;
        try {
            request = C2S_ReceiveInstanceAward.parseFrom(data);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        if(request == null){
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }
        int mapId = request.getMapId();
        int id = request.getRewardId();//领取的ID
        logger.info("领取奖励请求参数--->mapId" + mapId);
        logger.info("领取奖励请求参数--->rewardId" + id);
        InstanceMap instance = DataFactory.getInstance().getGameObject(DataFactory.INSTANCE_KEY, mapId);
        if(instance == null)
        {
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }


        InstanceStarBox starBox = instance.getInstanceStarBox(id);
        if(starBox == null)
        {
            logger.info("不存在宝箱id--->" + id);
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }


        InstanceInfo instanceInfo = (InstanceInfo) playerController.getPlayer().getExtInfo(InstanceInfo.class);
        InstanceMap instanceMap = instanceInfo.getInstanceMap().get(mapId);
        if(instanceMap == null){
            logger.info("该地图还未解锁");
            //返回给客户端
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.MAP_NOT_UNLOCK));
            return;
        }
        if(instanceMap.getHasReward().contains(id)){
            logger.info("已经领取过本次次奖励");
            //返回给客户端
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.GET_REWARD_ED));
            return;
        }


        int mapStars = 0;
        for(Level level : instanceMap.getFinishLevels()){
            mapStars += level.getMaxStars();
        }
        logger.info("用户总星数：" + mapStars + ", 请求星数： " + mapStars);
        if(mapStars < starBox.star)
        {
            logger.info("星级不满足条件" + mapStars);
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.CONDITION_ERROR));
            return;
        }



        DropGroup dropGroup = DataFactory.getInstance().getGameObject(DataFactory.DROP_GROUP_KEY, starBox.dropId);

        DropResult result = dropGroup.reward(playerController);

        instanceMap.getHasReward().add(id);

        S2C_ReceiveInstanceAward.Builder response = S2C_ReceiveInstanceAward.newBuilder();
        for(CommonData card : result.getCards())
        {
            response.addCard(card.parseCommonObject());
        }
        for(CommonData prop : result.getProps())
        {
            response.addProp(prop.parseCommonObject());
        }
        for(CommonData asset : result.getAssets())
        {
            response.addAsset(asset.parseCommonObject());
        }

        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Instance_ReceiveAward_VALUE, response.build().toByteArray());
    }

    private void addPassLevel(PlayerController playerController ,byte [] data) {

        C2S_PassLevel request = null;
        try {
            request = C2S_PassLevel.parseFrom(data);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        if(request == null){
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }

        int mapId = request.getMapId();
        int levelId = request.getLevelId();
        int stars = request.getStarts();

        InstanceInfo instanceInfo = (InstanceInfo) playerController.getPlayer().getExtInfo(InstanceInfo.class);
        logger.info("通过副本请求参数-->地图id : " + mapId);
        logger.info("通过副本请求参数-->关卡id : " + levelId);
        logger.info("通过副本请求参数-->通过星星数 : " + stars);
        logger.info("通过副本请求参数-->通过关卡前 ： " + instanceInfo.toString());
        //判断mapid和levelid是否合法
        InstanceMap instance = DataFactory.getInstance().getGameObject(DataFactory.INSTANCE_KEY, mapId);
        if(instance == null)
        {
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }

        if( stars > 3 || stars < 1){
            //返回给客户端
            logger.info("副本过关结果 ： " + "参数异常");
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }



        if(!instanceInfo.getCanPassMap().contains(mapId)){
            logger.info("副本过关结果 ： " + "地图未解锁");
            //返回给客户端
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.MAP_NOT_UNLOCK));
            return;
        }
        InstanceMap instanceMap = instanceInfo.getInstanceMap().get(mapId);

        //获取正在进行的副本
        if(instanceMap == null){ // 需要开启新的地图
//            //检查前一个地图是否都过关了
//            if(mapId > 1 ){
//                instanceMap = instanceInfo.getInstanceMap().get(mapId - 1);
//                if(instanceMap == null || instanceMap.getFinishLevels().size() != 10){
//                    //返回给客户端
//                    response.setResult(E_INSTANCE_PASS.INSTANCE_PASS_MAP_UNLOCK);
//                    playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Instance_PassLevel_VALUE, response.build().toByteArray());
//                    return;
//                }
//            }
            if(instanceInfo.getNextPassLevel().contains(levelId)){
                instanceMap = new InstanceMap();
                instanceMap.setId(mapId);
                Level lv = new Level();
                lv.setId(levelId);
                lv.setMaxStars(stars);
                instanceMap.addLevel(lv);
                instanceInfo.addInstanceMap(instanceMap);
                instanceInfo.changeNext();
            }else {
                //返回给客户端
                playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.MAP_NOT_UNLOCK));
                return;
            }

        }else {// 还在当前地图

            if(instanceInfo.getNextPassLevel().contains(levelId)){// 新的关卡
                Level lv = new Level();
                lv.setId(levelId);
                lv.setMaxStars(stars);
                instanceMap.addLevel(lv);
                instanceInfo.changeNext();
            }else if(instanceMap.getLevelMap().get(levelId) != null){//重复通过老的关卡
                Level level = instanceMap.getLevelMap().get(levelId);
                if(stars > level.getMaxStars()){
                    level.setMaxStars(stars);
                }
            }else {
                //返回给客户端
                playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.MAP_NOT_UNLOCK));
                return;
            }
        }

        S2C_PassLevel.Builder response = S2C_PassLevel.newBuilder();
        response.setMapId(mapId);
        response.setLevelId(levelId);
        response.setStarts(stars);
        //返回给客户端
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Instance_PassLevel_VALUE, response.build().toByteArray());
        logger.info("返回给客户端 ： " + response.toString());
        logger.info("通过关卡后 ： " + instanceInfo.toString());
//        getList(playerController, data);
    }


    private void requestLevelBattle(PlayerController playerController, byte [] data)
    {

        C2S_RequestLevelBattle request = null;
        try {
            request = C2S_RequestLevelBattle.parseFrom(data);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        if(request == null){
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }

        int mapId = request.getMapId();
        int levelId = request.getLevelId();

        Level level = DataFactory.getInstance().getGameObject(DataFactory.LEVEL_KEY, levelId);
        if(level == null || level.getInstanceId() != mapId)
        {
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }

        InstanceInfo instanceInfo = (InstanceInfo) playerController.getPlayer().getExtInfo(InstanceInfo.class);
        logger.info("副本战斗请求参数-->地图id : " + mapId);
        logger.info("副本战斗请求参数-->关卡id : " + levelId);
        //判断mapid和levelid是否合法

        InstanceMap instanceMap = instanceInfo.getInstanceMap().get(mapId);

        //获取正在进行的副本
        if(instanceMap == null){ // 需要开启新的地图
            if(!instanceInfo.getNextPassLevel().contains(levelId)){
                //返回给客户端
                playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.MAP_NOT_UNLOCK));
                return;
            }
        }

        MsgUtils.startBattle(playerController, level, E_BATTLE_TYPE.BATTLE_TYPE_PVE_INSTANCE);
//        ServerInfo serverInfo = ServerManager.getInstance().getFreeServer(E_ServerType.TCP_BATTLE);
//        if(serverInfo == null)
//        {
//            logger.info("战斗服务器没有开启!");
//            playerController.sendAlert(playerController, E_NOTIFY_TYPE.NOTIFY_TYPE_BATTLE_SERVER_ERROR);
//        }
//        else
//        {
//            String battleId = GameServer.getInstance().createBattleId();
//            serverInfo.sendBattleInit(battleId, E_BATTLE_TYPE.BATTLE_TYPE_PVE_INSTANCE_VALUE, playerController.getObjectIndex(), levelId + "", 0);
//
//            playerController.setBattleServerPort(serverInfo.getPort());
//
//            playerController.sendInstanceBattle(playerController, mapId, levelId, serverInfo.getIp(), serverInfo.getPort(), battleId);
//        }
    }

    private void getList(PlayerController playerController, byte[] data) {

        S2C_GetInstanceInfo.Builder response = S2C_GetInstanceInfo.newBuilder();
        C2S_GetInstanceInfo request = null;
        try {
            request = C2S_GetInstanceInfo.parseFrom(data);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        if(request == null){
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.PARAM_ERROR));
            return;
        }

        int targetMapId = request.getMapId();

        logger.info("获取关卡列表信息传入参数 ： " + " 地图id：" + targetMapId);


        InstanceInfo instanceInfo = (InstanceInfo) playerController.getPlayer().getExtInfo(InstanceInfo.class);
        InstanceMap targetMap = instanceInfo.getInstanceMap().get(targetMapId);
        if(targetMap == null && targetMapId != 0){
            playerController.sendAlert(E_NOTIFY_TYPE.NOTIFY_TYPE_WARN, WordFactory.getWord(WordFactory.MAP_NOT_UNLOCK));
            return;
        }

        logger.info("获取关卡列表信息 ： " + instanceInfo.toString());

        SGCommonProto.InstanceMap.Builder proInstanceMap;
        SGCommonProto.Level.Builder proLevel;
        for(InstanceMap map : instanceInfo.getInstanceList()){
            proInstanceMap = SGCommonProto.InstanceMap.newBuilder();
            proInstanceMap.setMapId(map.getId());
            for(Level lv : map.getFinishLevels()){
                proLevel = SGCommonProto.Level.newBuilder();
                proLevel.setMaxStars(lv.getMaxStars());
                proLevel.setLevelId(lv.getId());
                proLevel.setBoxReward(lv.isReceive());
                proInstanceMap.addLevels(proLevel);
            }
            for(Integer rewardId : map.getHasReward()){
                proInstanceMap.addReciverRewards(rewardId);
            }
            response.addMaps(proInstanceMap);
        }
        response.setMapId(targetMapId);

        //传入地图id为0的时候，请求最远处的地图信息
//        int targetIndex = targetMapId == 0 ? instanceInfo.getInstanceList().size() - 1 :
//                instanceInfo.getInstanceList().indexOf(targetMap);
//        response.setMapId(instanceInfo.getInstanceList().get(targetIndex).getId());
//        if(targetIndex == 0){ // 第一关
//            response.addMaps(getResultByInstance(instanceInfo.getInstanceList().get(targetIndex)));
//            if(instanceInfo.getInstanceList().size() > 1){
//                response.addMaps(getResultByInstance(instanceInfo.getInstanceList().get(targetIndex + 1)));
//            }
//        }else if(targetIndex == instanceInfo.getInstanceList().size() - 1){ //最后一关
//            response.addMaps(getResultByInstance(instanceInfo.getInstanceList().get(targetIndex - 1)));
//            response.addMaps(getResultByInstance(instanceInfo.getInstanceList().get(targetIndex)));
//        }else {
//            response.addMaps(getResultByInstance(instanceInfo.getInstanceList().get(targetIndex - 1)));
//            response.addMaps(getResultByInstance(instanceInfo.getInstanceList().get(targetIndex)));
//            response.addMaps(getResultByInstance(instanceInfo.getInstanceList().get(targetIndex + 1)));
//        }

//        for(InstanceMap map : instanceInfo.getInstanceList()){
//            response.addMaps(getResultByInstance(map));
//        }
        logger.info("返回给客户端关卡列表信息 ： " + response.toString());
        //返回给客户端
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Instance_GetInstanceInfo_VALUE, response.build().toByteArray());


//        InstanceMap.Builder proInstanceMap;
//        Level.Builder proLevel;
//        for(InstanceMap map : instanceInfo.getInstanceList()){
//            proInstanceMap = InstanceMap.newBuilder();
//            proInstanceMap.setMapId(map.getId());
//            for(Level lv : map.getFinishLevels()){
//                proLevel = Level.newBuilder();
//                proLevel.setMaxStars(lv.getMaxStars());
//                proLevel.setLevelId(lv.getId());
//                proLevel.setBoxReward(lv.isReceive());
//                proInstanceMap.addLevels(proLevel);
//            }
//            for(Integer rewardId : map.getHasReward()){
//                proInstanceMap.addReciverRewards(rewardId);
//            }
//            response.addMaps(proInstanceMap);
//        }


    }

    private SGCommonProto.InstanceMap.Builder getResultByInstance(InstanceMap map) {
        SGCommonProto.Level.Builder proLevel;
        SGCommonProto.InstanceMap.Builder  proInstanceMap = SGCommonProto.InstanceMap.newBuilder();
        proInstanceMap.setMapId(map.getId());
        for(Level lv : map.getFinishLevels()){
            proLevel = SGCommonProto.Level.newBuilder();
            proLevel.setMaxStars(lv.getMaxStars());
            proLevel.setLevelId(lv.getId());
            proInstanceMap.addLevels(proLevel);
        }
        for(Integer rewardId : map.getHasReward()){
            proInstanceMap.addReciverRewards(rewardId);
        }

        return proInstanceMap;
    }


}
